<?php

namespace App\Models\API;

use DB;
use Auth;
use App\Events\NewNotification;
use Illuminate\Database\Eloquent\Model;

class Activity extends Model
{
    // 追加值到结果集
    protected $appends = ['is_apply_activity', 'is_join_activity'];

    protected $fillable = [
        'user_id', 'title', 'theme', 'cover', 'start_time', 
        'end_time', 'details', 'number_of_people', 'address',
    ];

    public function getIsApplyActivityAttribute()
    {
        $userId = Auth::user()->id;
        // count结果储存至redis，首先读取redis
        return $this->activityApply()->where('user_id', $userId)->count();
    }

    public function getIsJoinActivityAttribute()
    {
        $userId = Auth::user()->id;
        // count结果储存至redis，首先读取redis
        return $this->activityJoin()->where('user_id', $userId)->count();
    }

    public function user()
    {
        return $this->belongsTo('App\Models\API\User');
    }

    public function activityApply()
    {
        return $this->hasMany('App\Models\API\ActivityApply');
    }

    public function activityJoin()
    {
        return $this->hasMany('App\Models\API\ActivityJoin');
    }

    public function activityComment()
    {
        return $this->hasMany('App\Models\API\ActivityComment');
    }

    public function apply($userInfo)
    {
    	$activityId = $this->id;
        
        $apply = new ActivityApply;
        $apply->activity_id = $activityId;
        $apply->user_id = $userInfo['user_id'];
        $apply->save();

    	return 'apply_succeed';
    }

    public function cancelApply($userInfo)
    {
    	$activityId = $this->id;

        $deleteApply = ActivityApply::where([
            ['activity_id', '=', $activityId],
            ['user_id' , '=', $userInfo['user_id']]
        ])->delete();

    	return 'cancel_apply_succeed';
    }

    public function joinUser($userInfo)
    {
    	$activityId = $this->id;
        // 首先删除此用户之前的申请
        $deleteApply = ActivityApply::where('user_id', '=', $userInfo['companion_id'])->delete();
        // 首次添加的用户直接加为好友，并向对方发送通知
        $this->addFriend($userInfo);

        $join = new ActivityJoin;
        $join->activity_id = $activityId;
        $join->user_id = $userInfo['companion_id'];
    	$join->save();

        // 通知活动参加成功
        $this->joinSucceed($userInfo['companion_id']);

    	return 'join_succeed';
    }

    public function cancelJoin($userInfo)
    {
        $activityId = $this->id;

        $deleteApply = ActivityJoin::where([
            ['activity_id', '=', $activityId],
            ['user_id' , '=', $userInfo['user_id']]
        ])->delete();

        // 通知发布者有人退出

        return 'cancel_join_succeed';
    }

    public function comment($data)
    {
        $activityId = $this->id;

        $comment = new ActivityComment;
        $comment->activity_id = $activityId;
        $comment->user_id = $data['user_id'];
        $comment->comment = $data['comment'];
        $comment->save();

        return 'comment_succeed';
    }

    // 双方添加好友
    private function addFriend($userInfo)
    {
        if (!$this->isFriend($userInfo['user_id'], $userInfo['companion_id'])) {
            $chatroom;

            if ($userInfo['user_id'] > $userInfo['companion_id']) {
                $chatroom = $userInfo['companion_id'].$userInfo['user_id'];
            }else{
                $chatroom = $userInfo['user_id'].$userInfo['companion_id'];
            }
            // 自己
            $newFriend = new Friend;
            $newFriend->user_id = $userInfo['user_id'];
            $newFriend->companion_id = $userInfo['companion_id'];
            $newFriend->chatroom = $chatroom;
            $newFriend->save();
            // 对方
            $newFriend = new Friend;
            $newFriend->user_id = $userInfo['companion_id'];
            $newFriend->companion_id = $userInfo['user_id'];
            $newFriend->chatroom = $chatroom;
            $newFriend->save();

            // 在这里要通知对方添加好友
            $this->addFriendSucceed($userInfo);
        }
    }

    private function isFriend($user_id, $companion_id)
    {
        $friend = Friend::where([
            ['user_id', '=', $user_id],
            ['companion_id', '=', $companion_id]
        ])->get();
        if (count($friend) === 0) {
            return false;
        }else{
            return true;
        }
    }

    // 通知用户活动参加成功
    private function joinSucceed($userId)
    {
        $activityId = $this->id;
        $title = $this->title;
        $detail = [
            'activity_id' => $activityId,
            'title' => $title,
            'sign' => '你已经成功加入活动了，快去和小伙伴打个招呼吧！'
        ];

        $notification = new Notification;
        $notification->user_id = $userId;
        $notification->type = 'join_succeed';
        $notification->detail = json_encode($detail); // json_decode()
        $notification->status = 0;
        $notification->save();

        event(new NewNotification($notification));
    }

    // 通知对方用户同意添加好友
    private function addFriendSucceed($userInfo)
    {
        $user = User::where('id', $userInfo['user_id'])->first();
        $detail = [
            'user_id' => $userInfo['user_id'],
            'user_name' => $user->user_name,
            'user_img' => $user->user_img,
            'sign' => '对方同意了你的申请，你们现在是好友了！'
        ];

        $notification = new Notification;
        $notification->user_id = $userInfo['companion_id'];
        $notification->type = 'add_friend_succeed';
        $notification->detail = json_encode($detail); // json_decode()
        $notification->status = 0;
        $notification->save();

        event(new NewNotification($notification));
    }
}
